package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.quanshu.change.view.InviteResgisActivity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.entity.AccountBalanceEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.BaseFragment;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.gui.profile.member.MemberInfoActivity;
import com.quanshu.exchange.ui.gui.qrcode.MyQrCodeActivity;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jye on 2017/12/6.
 */

public class ProfileFragment extends BaseFragment {

    @BindView(R.id.setting_profile_llt)
    LinearLayout settingProfileLlt;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.number_name_llt)
    RelativeLayout numberNameLlt;
    @BindView(R.id.head_photo_select)
    ImageView headPhotoSelect;
    @BindView(R.id.my_shop_car_rel)
    RelativeLayout myShopCarRel;
    @BindView(R.id.my_collect_rel)
    RelativeLayout myCollectRel;
    @BindView(R.id.delivery_address_rel)
    RelativeLayout deliveryAddressRel;
    @BindView(R.id.lianxi_kefu_rel)
    RelativeLayout lianxiKefuRel;
    @BindView(R.id.xitong_message_rel)
    RelativeLayout xitongMessageRel;
    @BindView(R.id.user_number)
    TextView userNumber;
    @BindView(R.id.qrcode_profile_llt)
    LinearLayout qrcodeProfileLlt;
    @BindView(R.id.right_image_two)
    ImageView rightImageTwo;
    @BindView(R.id.shop_car_image)
    ImageView shopCarImage;
    @BindView(R.id.my_collect_image)
    ImageView myCollectImage;
    @BindView(R.id.do_wallet)
    RelativeLayout doWallet;
    @BindView(R.id.login_layout)
    RelativeLayout loginLayout;
    @BindView(R.id.profile_top_layout)
    RelativeLayout profileTopLayout;
    Unbinder unbinder;
    @BindView(R.id.layout_member_info)
    RelativeLayout layoutMemberInfo;
    @BindView(R.id.layout_invite_register)
    RelativeLayout layoutInviteRegister;
    @BindView(R.id.profile_top_title)
    RelativeLayout profileTopTitle;
    private String userNameStr;
    private String userAvatar;//头像
    private UserEntity currentUser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        getBalance();
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        ImmersionBar.with(getActivity()).destroy();
    }

    public static ProfileFragment newInstance() {
        ProfileFragment f = new ProfileFragment();
        Bundle args = new Bundle();
        f.setArguments(args);
        return f;
    }

    @Override
    public int setFragmentLayoutID() {
        return R.layout.fragment_profile_layout;
    }

    @Override
    protected void initListener() {

        //我的二维码
        RxViewHelper.getInstance().clicks(qrcodeProfileLlt, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), MyQrCodeActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        });

        //设置 --
        RxViewHelper.getInstance().clicks(settingProfileLlt, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), SettingActivity.class);
            startActivity(intent);
        });

        //修改昵称
        RxViewHelper.getInstance().clicks(numberNameLlt, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), AmendUserNameActivity.class);
            intent.putExtra("userNameStr", userNameStr);
            startActivityForResult(intent, 7);
        });

        RxViewHelper.getInstance().clicks(headPhotoSelect, aVoid -> doShowPhotoDialog());


        //我的钱包
        RxViewHelper.getInstance().clicks(doWallet, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), MyWalletActivity.class);
            startActivity(intent);
        });


        //我的收藏
        RxViewHelper.getInstance().clicks(myCollectRel, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), MyFavoriteActivity.class);
            startActivity(intent);
        });

        //收货地址
        RxViewHelper.getInstance().clicks(deliveryAddressRel, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), DeliveryAddressActivity.class);
            startActivity(intent);
        });

        //联系客服
        RxViewHelper.getInstance().clicks(lianxiKefuRel, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), ServiceCenterActivity.class);
            startActivity(intent);
        });

        //系统消息
        RxViewHelper.getInstance().clicks(xitongMessageRel, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), SysMassageActivity.class);
            startActivity(intent);
        });

        // 会员推荐
        RxViewHelper.getInstance().clicks(layoutMemberInfo, aVoid -> {
            currentUser = MyApplication.getInstance().getCurrentUser();
            if (currentUser == null) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            Intent intent = new Intent(getActivity(), MemberInfoActivity.class);
            startActivity(intent);
        });

        RxViewHelper.getInstance().clicks(layoutInviteRegister, aVoid -> {
//            currentUser = MyApplication.getInstance().getCurrentUser();
//            if (currentUser == null) {
//                Intent intent = new Intent(getActivity(), LoginActivity.class);
//                startActivity(intent);
//                return;
//            }
            Intent intent = new Intent(getActivity(), InviteResgisActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        ImmersionBar.with(getActivity()).titleBar(profileTopTitle).init();
    }

    private void initViewInfo() {
        currentUser = MyApplication.getInstance().getCurrentUser();
        if (currentUser == null) {
            numberNameLlt.setVisibility(View.GONE);
            loginLayout.setVisibility(View.VISIBLE);
        } else {
            numberNameLlt.setVisibility(View.VISIBLE);
            loginLayout.setVisibility(View.GONE);
            GlideUtils.setRoundImageView(getActivity(), MyApplication.getInstance().getCurrentUser().getAvatar(), R.drawable.icon_person_img_2_0, headPhotoSelect);
            if (!TextUtils.isEmpty(currentUser.getNickname())) {
                userName.setText(currentUser.getNickname());
            }
            userNumber.setText(currentUser.getMobile() + "");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 7) {
                userNameStr = data.getStringExtra("userName");
                userName.setText(userNameStr);
                currentUser.setNickname(userNameStr);
                MyApplication.getInstance().setCurrentUser(currentUser);
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                String path = selectList.get(0).getCutPath();
                GlideUtils.setRoundImageView(getActivity(), path, R.drawable.icon_person_img_2_0, headPhotoSelect);
                File file = new File(path);
                if (file != null && file.exists()) {
                    upLoadFile(file);
                } else {
                    ToastHelper.toast("上传图片错误");
                }
            }
        }
    }

    private void doShowPhotoDialog() {
        currentUser = MyApplication.getInstance().getCurrentUser();
        if (currentUser == null) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return;
        }
        DialogPhotoSelect dialogPhotoSelect = new DialogPhotoSelect(getActivity());
        dialogPhotoSelect.show();
        dialogPhotoSelect.getAlbumSubject().subscribe(o -> {
            PictureSelector.create(ProfileFragment.this)
                    .openGallery(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
        dialogPhotoSelect.getTakePhotoSubject().subscribe(o -> {
            PictureSelector.create(ProfileFragment.this)
                    .openCamera(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
    }

    private void upLoadFile(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part avatar = MultipartBody.Part.createFormData("img", file.getName(), requestFile);
        RequestBody memberId = RequestBody.create(MediaType.parse("multipart/form-data"),
                MyApplication.getInstance().getCurrentUser().getMemberid());
        RequestBody key = RequestBody.create(MediaType.parse("multipart/form-data"),
                AppUtils.getSignParams(MyApplication.getInstance().getCurrentUser().getMemberid()));
        NetClient.getInstance()
                .getShopService(UserInterface.class)
                .uploadUserAvatar(key, avatar, memberId)
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> response) {
                        String data = response.getData();
                        userAvatar = data;
                        currentUser.setAvatar(userAvatar);
                        MyApplication.getInstance().setCurrentUser(currentUser);
                        GlideUtils.setRoundImageView(getActivity(), userAvatar, R.drawable.icon_person_img_2_0, headPhotoSelect);

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.print("======onResume====");
        initViewInfo();
        getBalance();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.print("======onHiddenChanged====" + hidden);
        if (hidden == false) {
            initViewInfo();
            getBalance();
        }
        if (!hidden) {
            ImmersionBar.with(getActivity()).titleBar(profileTopTitle).init();
        }
    }

    //左右相邻的Fragment切换时执行
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        LogUtil.print("======setUserVisibleHint====" + isVisibleToUser);
        if (isVisibleToUser) {
            getBalance();
        }
    }

    //获取账户余额
    private void getBalance() {

        if (currentUser != null) {
            NetClient.getInstance().getShopService(ShopInterface.class)
                    .getBalance(currentUser.getId())
                    .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                    .subscribe(new BaseObserver<BaseResponse<AccountBalanceEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<AccountBalanceEntity> response) {
                            if (response.getCode() == 1) {
                                currentUser.setScore(response.getData().getScore());
                                currentUser.setGp(response.getData().getGP());
                                MyApplication.getInstance().setCurrentUser(currentUser);
                            }
                        }

                        @Override
                        public void onFailure(Throwable e) {
                            LogUtil.printException(e);
                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
